/*
 *	xstring.c
 *	  part of the xlibrary by SunDEV (http://sundev.890m.com)
 *
 *	Changelog :
 *	  ##-##-## : First public release
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "xcommon.h"

#include "xstring.h"

#include "xmalloc.h"

char *endName(char delimiter, char *path) {
	char *name=strrchr(path, delimiter);
	return name?name+1:path;
}

int cmpext(char *fn, char *ext) {
	if(!fn || !ext || strlen(fn)<strlen(ext)) return 1;
	return !!strcasecmp(&fn[strlen(fn)-strlen(ext)], ext);
}

char *xstrdup(char *str) {
	if(!str) return NULL;

	char *tmp=(char *)xmalloc(strlen(str)+1);
	strcpy(tmp, str);

	return tmp;
}

void *xmemdup(void *data, u32 dataSize) {
	if(!data || !dataSize) return NULL;

	void *tmp=xmalloc(dataSize);
	memcpy(tmp, data, dataSize);

	return tmp;
}

/**
 * see http://www.jb.man.ac.uk/~slowe/cpp/itoa.html
 *
 * C++ version 0.4 char* style "itoa":
 * Written by Lukás Chmela
 * Released under GPLv3.
 */
char* itoa(int value, char* result, int base) {
	// check that the base if valid
	if(base<2 || base>36) { *result=0; return result; }

	char* ptr=result, *ptr1=result, tmp_char;
	int tmp_value;

	do {
		tmp_value=value;
		value/=base;
		*ptr++="zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35+(tmp_value-value*base)];
	} while(value);

	// Apply negative sign
	if(tmp_value<0) *ptr++='-';
	*ptr--=0;
	while(ptr1<ptr) {
		tmp_char = *ptr;
		*ptr--= *ptr1;
		*ptr1++ = tmp_char;
	}
	return result;
}

